package org.lmind.example.common.service.mail;

import java.io.File;
import java.util.ArrayList;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;

import org.lmind.example.common.api.Mail;
import org.lmind.example.common.core.UnhandledException;

public class DefaultMail implements Mail {
	
	private MimeBodyPart contentPart;
	
	private ArrayList<MimeBodyPart> attachments = new ArrayList<MimeBodyPart>();
	
	private String subject;
	
	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}
	
	public void setBody(String html, String mimeType) {
		try {
			contentPart = new MimeBodyPart();
			contentPart.setContent(html, mimeType);
		} catch (MessagingException e) {
			throw new UnhandledException(e);
		}
	}
	
	public void addAttachment(File file, String name) {
		try {
			FileDataSource fileDataSource = new FileDataSource(file);
			if (name == null)
				name = fileDataSource.getName();
			MimeBodyPart mimeBodyPart = new MimeBodyPart();
			mimeBodyPart.setFileName(name);
			mimeBodyPart.setDataHandler(new DataHandler(fileDataSource));
			mimeBodyPart.setHeader("Content-ID", "<" + name + ">");
			attachments.add(mimeBodyPart);
		} catch (MessagingException e) {
			throw new UnhandledException(e);
		}
	}
	
	public MimeMultipart createMimeMultipart() {
		try {
			MimeMultipart mimeMultipart = new MimeMultipart("mix");
			mimeMultipart.addBodyPart(contentPart);
			for (MimeBodyPart part : attachments) {
				mimeMultipart.addBodyPart(part);
			}
			return mimeMultipart;
		} catch (MessagingException e) {
			throw new UnhandledException(e);
		}
	}
}
